package com.wzh.yebServe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.yebServe.pojo.Menu;
import com.wzh.yebServe.pojo.Role;
import com.wzh.yebServe.utils.JwtTokenUtils;
import com.wzh.yebServe.mapper.UserMapper;
import com.wzh.yebServe.pojo.ResultBean;
import com.wzh.yebServe.pojo.User;
import com.wzh.yebServe.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wzh
 * @create 2022/11/6 12:06
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserMapper userMapper;



    @Override
    public ResultBean login(String username, String password, String code,HttpServletRequest request) {
        String captcha =(String) request.getSession().getAttribute("captcha");
        if (code==null||!code.equalsIgnoreCase(captcha)){
            return ResultBean.error("验证码输入错误，请重新输入");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails==null||!passwordEncoder.matches(password,userDetails.getPassword())){
            return ResultBean.error("用户名或者密码错误");
        }
        if (userDetails.isEnabled()){
            return ResultBean.error("该用户已经停用");
        }
      //更新security登录用户对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken= new
                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

      //登录成功后将token返回给前端
        String token=jwtTokenUtils.generateToken(userDetails);
        Map<String,String > map=new HashMap<>();
        map.put("token",token);
        //头部信息给前端，让他放在请求头当中
        map.put("tokenHeader",tokenHead);

        return ResultBean.success("登录成功",map);
    }


    @Override
    public ResultBean getInfo(String username) {
        User user = query().eq("username", username).one();
        user.setPassword(null);
        user.setRoles(getRoles(user.getId()));
        return ResultBean.success(null,user);
    }

    @Override
    public List<Role> getRoles(Integer userId) {
        return userMapper.getRoles(userId);
    }

    @Override
    public User getUserByUsername(String username) {
        User user = this.query().eq("username", username).one();
        return user;
    }

    @Override
    public List<User> getAllUsers(String keywords) {
        return userMapper.getAllUsers(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId(),keywords);
    }

    @Override
    public ResultBean updateUser(User user) {
        boolean b = updateById(user);
        if (b) {
            return ResultBean.success("更新成功");
        }
        return ResultBean.error("更新失败");
    }

    @Override
    public ResultBean deleteUser(Integer id) {
        boolean b = removeById(id);
        if (b) {
            return ResultBean.success("删除成功");
        }
        return ResultBean.error("删除失败");
    }

    @Override
    public ResultBean updateUserPassword(String oldPass, String pass, Integer adminId) {
        User user = userMapper.selectById(adminId);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if(encoder.matches(oldPass,user.getPassword())){
            user.setPassword(encoder.encode(pass));
            boolean b = updateById(user);
            if (b){
                return ResultBean.success("更新成功");
            }
        }
        return ResultBean.error("更新失败");
    }
}
